package com.dys.loginhander;

import com.dys.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @className: com.dys.loginhander.LoginServlet
 * @description: 用来校验登录的, 登录成功将用户信息存户HttpSession, 否则回到登录页
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/20 22:50
 */
@WebServlet(urlPatterns = "/loginServlet.do")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username: " + username);
        System.out.println("password: " + password);

        // 校验用户名和密码
        if ("admin".equals(username) && "123".equals(password)) {
            User user = new User(1, "admin", "123");
            // 将用户信息存入HttpSession中
            HttpSession httpSession = req.getSession();
            httpSession.setAttribute("user", user);
            // 登录成功，跳转到main.html
            resp.sendRedirect(req.getContextPath() + "/mainServlet.do");
        } else {
            // 登录失败，回到login.html
            resp.sendRedirect(req.getContextPath() + "/login.html");
        }
    }
}
